const Pool = require('../Tools/TestCenterPool').pool;
const _ = require('lodash');
const moment = require('moment');
const jiraDbModels = require('./jiraDbModel');
const JiraModel = require('./JiraModel')


const ReportData = require('./reportData')
class TestReportModel {
  async insert(projectid,version){
    try{
      let testData = {
        suggest:0,
        newbug:0,
        deadly:0,
        serious:0,
        commom:0,
        tips:0,
        verify:0,
        verifyfail:0,
        totalbug:0,
        block:0        
      }
      let sql = `INSERT INTO test_report(project_id,version,name,testdata)
      SELECT ?,?,(SELECT a.name FROM test_project AS a WHERE a.id = ${projectid}),?
      FROM DUAL`;
      let sql_params = new Array(2);
      sql_params[0] = projectid 
      sql_params[1] = version
      sql_params[2] = JSON.stringify(testData)
      let result = await Pool.queryAsync(sql,sql_params);
      let reportId =0;
      if(result.affectedRows==1){
        reportId =result.insertId
      }
      return reportId;
    }catch(error){
      return error;
    }    
  }

  async getTestReport(){
    try{
      let sql = `SELECT * FROM test_report WHERE 1=1 ORDER BY id DESC `;
      let count_sql = `SELECT count(*) FROM test_report WHERE 1=1`

      let rows = await Pool.queryAsync(sql);
      let count = await Pool.queryAsync(count_sql);
      count = count.map((c) => {
        return c['count(*)'];
      })[0];
      let reportList = rows.map((r) =>{
        const arr = [null,'']
        return {
          key:r.id,
          projectId: r.project_id,
          name : r.name,
          version : r.version,
          status : r.status,
          testResult : r.status ===0 ? '不通过':(r.status===1 ? '通过':''),
          testStatus:r.status ===2? '未开始':(r.status===3? '进行中':'已完成'),
          startTime :  _.isNull(r.test_start_time) ? '--' : moment(r.test_start_time).format('YYYY-MM-DD'),
          endTime :  _.isNull(r.test_end_time) ? '--' : moment(r.test_end_time).format('YYYY-MM-DD'),
          workload : _.isNull(r.workload) ? 0:r.workload,
          tester : _.isNull(r.tester) ? []:r.tester.split('--'),
          state:r.state
        }
      })
      return { reportList: reportList, count: count }
    }catch(error){
      return error
    }
  }

  async delete(id,version){
    try{
      let delete_report_sql = `DELETE FROM test_report WHERE project_id=${id} AND version = '${version}'`;
      let result = await Pool.queryAsync(delete_report_sql);
      return result.affectedRows;
    }catch(error){
      return error  
    }
  }

  async editBasicReport(report){
    try{      
      let sql = `UPDATE test_report r SET r.status = ${report.status}`
      
      if(report.startTime != null){
        let sql_2= `,r.test_start_time = '${report.startTime}'`
        sql +=sql_2
      }

      if(report.endTime !=null){
        let sql_3 =`,r.test_end_time = '${report.endTime}'`
        sql+=sql_3
      }

      if(report.workload !=null){
        let sql_4 =`,r.workload = '${report.workload}'`
        sql+=sql_4
      }

      if(report.tester != null){
        let sql_5 =`,r.tester = '${report.tester}'`
        sql+=sql_5
      }

      if(report.network !=null){
        let sql_6 =`,r.network = '${report.network}'`
        sql += sql_6
      }

      if(report.testRange != null){
        let sql_7 = `,r.testrange = '${report.testRange}'`
        sql+=sql_7
      }

      if(report.equipment !=null){
        let sql_8 =`,r.equipment = '${report.equipment}'`
        sql+=sql_8
      }

      if(report.type != null){
        let sql_9 =`,r.type = '${report.type}'`
        sql+=sql_9
      }
      let sql_1 = ` WHERE r.id = ${report.id}`
      sql +=sql_1
      let result = await Pool.queryAsync(sql);
      return result.affectedRows;           
    }catch(error){
      console.log('123...',error)
      return error
    }
  }

  async editTextReport(report){
    try{
      let type = report.type
      let texttype = (type === 1? 'modify':(type ===2? 'summary':'risk'))
      let text = report.text;
      let id = report.id;
      let sql = `UPDATE test_report r SET r.${texttype} = '${text}' WHERE r.id = ${id}`
      let result = await Pool.queryAsync(sql);
      return result.affectedRows;
    }catch(error){
      return error
    }
  }

  async queryActiveReport(id){
    try{
      let sql = `SELECT * FROM test_report WHERE id = ${id}`
      let row = await Pool.queryAsync(sql);
      let r = row[0]
      const arr = [null,'']
      let acticeReport = {
        key:r.id,
        projectId: r.project_id,
        name : r.name,
        version : r.version,
        status : r.status,
        testResult : r.status ===0 ? '不通过':(r.status===1 ? '通过':''),
        testStatus:r.status ===2? '未开始':(r.status===3? '进行中':'已完成'),
        startTime :  _.isNull(r.test_start_time) ? '--' : moment(r.test_start_time).format('YYYY-MM-DD'),
        endTime :  _.isNull(r.test_end_time) ? '--' : moment(r.test_end_time).format('YYYY-MM-DD'),
        workload : _.isNull(r.workload) ? 0:r.workload,
        tester : _.isNull(r.tester) ? []:r.tester.split('--'),
        network : arr.indexOf(r.network)>-1 ? []:r.network.split('--'),
        type: r.type? r.type:'pc',
        testRange :arr.indexOf(r.testrange)>-1 ? []:r.testrange.split('--'),
        equipment :arr.indexOf(r.equipment)>-1 ? []:r.equipment.split('--'),
        testdata :  JSON.parse(r.testdata),
        modify : _.isNull(r.modify) ? '':r.modify,
        summary : _.isNull(r.summary) ? '':r.summary,
        risk : _.isNull(r.risk) ? '':r.risk,
        state:r.state,
      } 
      return  acticeReport
    }catch(error){
      console.log(error)
      return error
    }
  }

  async queryReportExist(projectId,version){
    let sql = `SELECT * FROM test_report WHERE project_id = ${projectId} AND version = '${version}'`
    let row = await Pool.queryAsync(sql);
    if(row.length==0){
      return true
    }else{
      return false
    }
  }

  async passRate(projectlist){

    let passRateList =[]
    for(var i=0;i<projectlist.length;i ++){
      let p = projectlist[i]
      let testcount_sql = `SELECT COUNT(*) as count FROM test_report WHERE project_id =${p.id} AND (status = 0 OR status = 1)`
      let passcount_sql = `SELECT COUNT(*) as count FROM test_report WHERE project_id =${p.id} AND status = 1`     
      
      let testcount_row = await Pool.queryAsync(testcount_sql)
      let passcount_row = await Pool.queryAsync(passcount_sql)
      
      let passRate = testcount_row[0].count ===0? 0:(passcount_row[0].count/testcount_row[0].count)*100
      let value = 0
      if(passRate>=90){
        value = 5
      }else if(passRate>=80){
        value = 4
      }else if(passRate>=70){
        value = 3
      }else if(passRate>=60){
        value = 2
      }else if(passRate>0){
        value = 1
      }else{
        value = 0
      }
      passRateList.push({'name':p.name,'label':'测试通过率','value':value})

    }

    return passRateList
  }

  async setTestData(pname,version){
    try{
      let deadly = await jiraDbModels.JiraDbBugSeverity(pname,version,'致命')
      let serious =await jiraDbModels.JiraDbBugSeverity(pname,version,'严重')
      let commom = await jiraDbModels.JiraDbBugSeverity(pname,version,'一般')
      let suggest = await jiraDbModels.JiraDbBugSeverity(pname,version,'建议')
      let tips = await jiraDbModels.JiraDbBugSeverity(pname,version,'提示')
      let block = await jiraDbModels.JiraDbHandingCount(pname)
      let totalbug = await jiraDbModels.JiraDbTotalBug (pname)
     // let verify = await  JiraModel.getReturnCountByVersion(pname,version)
    

      let verify = await ReportData.getRCV(pname,version)
      let reopen = await  ReportData.getReopenCountByVersion(pname,version)
      let testData = {
        suggest:suggest,
        newbug:deadly+serious+commom+tips,
        deadly:deadly,
        serious:serious,
        commom:commom,
        tips:tips,
        verify:verify,
        verifyfail:reopen,
        totalbug:totalbug,
        block:block        
      }
      testData = JSON.stringify(testData)
      let sql =`UPDATE test_report r SET r.testdata = '${testData}' WHERE name ='${pname}' AND version = '${version}'`
      let result = await Pool.queryAsync(sql);
      return result.affectedRows;
    }catch(error){
      throw error
    }
  } 

  async setTestState(reportId,realname,state){
    try{
      let sql = `UPDATE test_report r SET r.state = ${state}, r.real_name ='${realname}'  WHERE id =${reportId}`
      let result = await Pool.queryAsync(sql)
      return result.affectedRows
    }catch(error){
     // console.log('err@@',error)
      throw error
    }
  }

  async updateTestStatus(name,version,value){
    try{
      let sql = `UPDATE test_report  SET status= ${value} WHERE name ='${name}' AND version = '${version}'`
      let result = await Pool.queryAsync(sql)
      return result.affectedRows
    }catch(error){
      throw error
    }
  }


  async insertBasicData(array){
    try{  
      array.map((r)=>{
        let sql = `SELECT * FROM report_basic_data WHERE name = '${r.name}'`
        let res;
        (async() =>{
          res = await Pool.queryAsync(sql)
          if(res.length ==0){
            let sql1 = `INSERT INTO report_basic_data SET name = '${r.name}',type ='${r.type}'`
            let res2 = await Pool.queryAsync(sql1)
          }
        })()
        
      })
      
      return true
    }catch(error){
      console.log(error)
      throw error
    }
  }

  async getDataArray(){
    try{
      let sql = `SELECT * FROM report_basic_data`
      let res = await Pool.queryAsync(sql)
      let pc=[]
      let web=[]
      let mobile=[]
      let network=[]
      let range =[]
      res.map((r)=>{
        switch(r.type){
          case 'pc':
            pc.push(r.name)
            break
          case 'web':
            web.push(r.name)
            break
          case '移动端':
            mobile.push(r.name)
            break
          default:
            break    
        }
      })
      return {pc:pc,web:web,mobile:mobile}
    }catch(error){
      throw error
    }
  }

  async deleteBasicData(array){
    try{
      array.map((r)=>{
        let sql = `DELETE FROM report_basic_data  WHERE name='${r.name}'`
        (async()=>{
          let res = await Pool.queryAsync(sql)
        })()
      })
      return true
    }catch(error){
      throw error
    }
  }

  async updateTestStartTime(testRecordId){
    try{
      let date = new Date();
      let year = date.getFullYear()
      let month = date.getMonth()+1;
      let day = date.getDate();
      let today = `${year}-${month}-${day}`
      let sql = `UPDATE test_report r SET r.test_start_time = '${today}'  WHERE 
      project_id in (SELECT project_id FROM test_record WHERE id = ${testRecordId}) 
      AND version IN (SELECT version_name FROM test_record WHERE id = ${testRecordId})`

      let res = await Pool.queryAsync(sql)
      return res.affectedRows

    }catch(error){
      throw error
    }

  }
}



module.exports = new TestReportModel();
